import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:get/get.dart';
import 'package:nft_shop/my/model/models.dart';
import 'package:nft_shop/my/page/notice/home_announcement_page.dart';
import 'package:nft_shop/net/service_repository.dart';
import 'package:nft_shop/res/constant.dart';
import 'package:nft_shop/res/global.dart';
import 'package:nft_shop/widgets/load_image.dart';
import 'package:nft_shop/widgets/status_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomeNoticeListPage extends StatefulWidget {
  const HomeNoticeListPage({Key? key, required this.presentIndex})
      : super(key: key);

  final int presentIndex;

  @override
  _HomeNoticeListPageState createState() => _HomeNoticeListPageState();
}

class _HomeNoticeListPageState extends State<HomeNoticeListPage>
    with AutomaticKeepAliveClientMixin {
  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 当前第几页
  int currentPageNum = pageNumFirst;

  /// 分页条目数量
  int pageSize = 20;

  /// 页面数据
  List list = [];

  ///状态
  int _status = LoadStatusType.loading;

  ///刷新组件
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  int get status => _status;

  set status(int value) {
    _status = value;
    setState(() {});
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refresh();
  }

  ///获取数据
  Future<List> loadData({int? pageNum}) async {
    if (widget.presentIndex == 0) {
      return await ServiceRepository.fetchBanners(type: 2);
    } else {
      return await ServiceRepository.userMessage();
    }
  }

  /// 下拉刷新
  ///
  /// [init] 是否是第一次加载
  /// true:  Error时,需要跳转页面
  /// false: Error时,不需要跳转页面,直接给出提示
  Future<List?> refresh({bool init = false}) async {
    try {
      currentPageNum = pageNumFirst;
      var data = await loadData(pageNum: pageNumFirst);
      if (data.isEmpty) {
        refreshController.refreshCompleted(resetFooterState: true);
        list.clear();
        status = LoadStatusType.empty;
      } else {
        list.clear();
        list.addAll(data);
        refreshController.refreshCompleted();
        // 小于分页的数量,禁止上拉加载更多
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          //防止上次上拉加载更多失败,需要重置状态
          refreshController.loadComplete();
        }
        status = LoadStatusType.success;
      }
      return data;
    } catch (e, s) {
      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (init) list.clear();
      refreshController.refreshFailed();
      // setError(e, s);
      return null;
    }
  }

  /// 上拉加载更多
  Future<List?> loadMore() async {
    try {
      var data = await loadData(pageNum: ++currentPageNum);
      if (data.isEmpty) {
        currentPageNum--;
        refreshController.loadNoData();
      } else {
        list.addAll(data);
        if (data.length < pageSize) {
          refreshController.loadNoData();
        } else {
          refreshController.loadComplete();
        }
        setState(() {});
      }
      return data;
    } catch (e, s) {
      currentPageNum--;
      refreshController.loadFailed();
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Builder(builder: (context) {
      if (status != LoadStatusType.success) {
        return StatusViews(status);
      }
      return ListView.builder(
        itemCount: list.length,
        itemBuilder: (context, int index) {
          if (widget.presentIndex == 0) {
            return _buildItem1(list[index]);
          } else {
            return _buildItem2(list[index]);
          }
        },
      );
    });
  }

  Widget _buildItem1(Article model) {
    return InkWell(
      onTap: () async {
        // await ServiceRepository.fetchBanners(type: 2,);
        Get.to(AnnouncementPage(
          // title: model.title ?? "",
          title: "系统公告",
          content: model.content ?? "",
        ));
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        decoration: BoxDecoration(
            border: Border(
          bottom: Divider.createBorderSide(context,
              color: Global.kTheme.colorLine, width: 1),
        )),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SizedBox(
              height: 80,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  SizedBox(
                    width: Get.width - 32 - 5 - 110,
                    child: Text(
                      model.title ?? "",
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontSize: 14,
                          fontFamily: Global.mySemiboldFont,
                          color: Global.kTheme.textPrimary6),
                    ),
                  ),
                  Text(
                    model.createTime ?? "",
                    style: TextStyle(
                        fontSize: 12,
                        fontFamily: Global.myRegularFont,
                        color: Global.kTheme.inputHint1),
                  ),
                ],
              ),
            ),
            Spacer(),
            // Container(
            //   width: 6,
            //   height: 6,
            //   decoration: BoxDecoration(
            //     color: Colors.red,
            //     borderRadius: BorderRadius.circular(4),
            //   ),
            // ),
            SizedBox(
              width: 5,
            ),
            ClipRRect(
              borderRadius: BorderRadius.all(Radius.circular(10)),
              child: LoadImage(
                model.thumb ?? "",
                fit: BoxFit.cover,
                width: 110,
                height: 80,
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _buildItem2(MemberNotice model) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
          border: Border(
        bottom: Divider.createBorderSide(context,
            color: Global.kTheme.colorLine, width: 1),
      )),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                model.title ?? "",
                style: TextStyle(
                    fontSize: 14,
                    fontFamily: Global.mySemiboldFont,
                    color: Global.kTheme.textPrimary6),
              ),
              SizedBox(
                height: 2,
              ),
              SizedBox(
                width: Get.width - 32,
                child: Text(
                  model.content ?? "",
                  style: TextStyle(
                      fontSize: 12,
                      fontFamily: Global.mySemiboldFont,
                      color: Global.kTheme.inputHint1),
                ),
              ),
              SizedBox(
                height: 2,
              ),
              Text(
                model.createTime ?? "",
                style: TextStyle(
                    fontSize: 12,
                    fontFamily: Global.myRegularFont,
                    color: Global.kTheme.inputHint1),
              ),
            ],
          ),
          // Spacer(),
          // Container(
          //   width: 6,
          //   height: 6,
          //   decoration: BoxDecoration(
          //     color: Colors.red,
          //     borderRadius: BorderRadius.circular(4),
          //   ),
          // ),
          // SizedBox(
          //   width: 5,
          // ),
          // LoadAssetImage(
          //   "next_icon",
          //   width: 7,
          //   height: 12,
          // ),
        ],
      ),
    );

    //   InkWell(
    //   onTap: () async {
    //     // await ServiceRepository.fetchBanners(type: 2,);
    //     Get.to(AnnouncementPage(
    //       title: model.title ?? "",
    //       content: model.content ?? "",
    //     ));
    //   },
    //   child:
    //   ,
    // );
  }
}
